#include <stdio.h>
#include "msg_queue.h"
#include "control.h"
#include "voice_interface.h"
#include "socket_interface.h"
#include "smoke_interface.h"
#include "receive_interface.h"
#include <stdlib.h>
#include "global.h"
#include "wiringPi.h"

int main()
{
    mqd_t mqd = -1;
    int control_num = 0;
    pthread_t *tid = NULL;
    // 头指针
    struct control *control_head = NULL;
    // 临时指针
    struct control *pcontrol = NULL;
    ctr_info_t control_info;

    // wiringPi初始化
    if (-1 == wiringPiSetup())
    {
        printf("%s|%s|%d\n", __FILE__, __FUNCTION__, __LINE__);
        printf("wiringPiSetup failed!\n");
        return -1;
    }
    // 创建消息队列
    mqd = msg_queue_create();
    if (mqd == -1)
    {
        printf("%s|%s|%d\n", __FILE__, __FUNCTION__, __LINE__);
        printf("Error in creating message queue\n");
        return -1;
    }

    // 加入控制链表
    control_head = add_voice_to_control(control_head);
    control_head = add_socket_to_control(control_head);
    control_head = add_somke_to_control(control_head);
    control_head = add_receive_to_control(control_head);

    control_info.mqd = mqd;
    control_info.control_head = control_head;

    pcontrol = control_head;
    // 给设备控制统一做初始化
    while (pcontrol != NULL)
    {
        pcontrol->init();
        pcontrol = pcontrol->next;
        control_num++;
        printf("%s|%s|%d:%d\n", __FILE__, __FUNCTION__, __LINE__, control_num);
    }

    tid = malloc(sizeof(pthread_t) * control_num);
    pcontrol = control_head;
    // 创建线程
    for (int i = 0; i < control_num; i++)
    {
        printf("%s|%s|%d\n", __FILE__, __FUNCTION__, __LINE__);
        pthread_create(&tid[i], NULL, pcontrol->get, (void *)&control_info);
        pcontrol = pcontrol->next;
    }

    // 等待线程退出
    for (int i = 0; i < control_num; i++)
    {
        printf("%s|%s|%d\n", __FILE__, __FUNCTION__, __LINE__);
        pthread_join(tid[i], NULL);
    }

    pcontrol = control_head;
    while (pcontrol != NULL)
    {
        printf("%s|%s|%d\n", __FILE__, __FUNCTION__, __LINE__);
        pcontrol->final();
        pcontrol = pcontrol->next;
    }

    // 销毁消息队列
    msg_queue_final(mqd);

    return 0;
}